package jwtRequest

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"month_zg5/client/common/global"
	"net/http"
	"time"
)

func AuthToken(userid uint) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = time.Now().Unix() + 86400 //过期时间 一个月
	claims["id"] = userid
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(global.ClientConfig.AesConf.Key))
}
func ParseToken() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		tokenString := ctx.Request.Header.Get("x-token")
		if tokenString == "" {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"msg": "请登录",
			})
			ctx.Abort()
			return
		}

		token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
			return []byte(global.ClientConfig.AesConf.Key), nil
		})
		if err != nil {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"msg": "token格式有误",
			})
			ctx.Abort()
			return
		}
		if int64(token.Claims.(jwt.MapClaims)["ext"].(float64)) < time.Now().Unix() {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"msg": "token已经过期",
			})
			ctx.Abort()
			return
		}
	}
}
